package com.yesep.learn.jwt.handler;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import com.yesep.learn.jwt.common.R;
import com.yesep.learn.jwt.config.JWTTokenConfig;
import com.yesep.learn.jwt.util.ServletUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * @Description: 用户登录系统成功后 需要做的业务操作 当用户登录系统成功后则会进入到此类并执行相关业务
 */
@Slf4j
public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler {

	@Autowired
	private JWTTokenConfig jwtTokenConfig;

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
		UserDetails user = (UserDetails) authentication.getPrincipal();
		String token = jwtTokenConfig.generateToken(user);
		R<String> ok = R.me(HttpServletResponse.SC_OK, "令牌申请成功");
		ok.setPayload(jwtTokenConfig.wrapToken(token));
		ServletUtils.writeValueAsString(ok, response);
	}
}
